package com.nolon.flange.fragment

import android.Manifest
import android.os.Bundle
import android.os.Environment
import android.view.LayoutInflater
import android.view.View
import android.view.View.INVISIBLE
import android.view.View.VISIBLE
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.preference.PreferenceManager
import com.nolon.flange.R
import com.nolon.flange.databinding.FragmentFlangeExportBinding
import com.nolon.flange.extensions.toast
import com.nolon.flange.viewmodel.ExportViewModel
import com.nolon.flange.viewmodel.FlangeViewModel
import com.permissionx.guolindev.PermissionX
import java.text.SimpleDateFormat
import java.util.*


class FlangeExportFragment(private val parent: AppCompatActivity) : Fragment() {
    private var _binding: FragmentFlangeExportBinding? = null
    private val bd get() = _binding!!

    private val flangeViewModel by lazy { ViewModelProvider(parent).get(FlangeViewModel::class.java) }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentFlangeExportBinding.inflate(inflater, container, false)
        return bd.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initView()
        initData()
    }

    private fun initData() {
        val exportViewModel = ExportViewModel()
        with(exportViewModel) {
            flangeViewModel.exportViewModel = this
            bd.export = this

            val exportHoles = PreferenceManager.getDefaultSharedPreferences(requireContext())
                .getBoolean(getString(R.string.pref_export_hole), false)
            exportViewModel.exportHoles.set(exportHoles)
            val namePattern = PreferenceManager.getDefaultSharedPreferences(requireContext())
                .getString(getString(R.string.pref_with_date), "")
            exportFilePattern.set(namePattern)
            val formatter = SimpleDateFormat(namePattern, Locale.getDefault())
            exportFileHint.set("文件名（项目名${formatter.format(Date())})")
        }

        flangeViewModel.solutions.observe(viewLifecycleOwner) {
            bd.exportLayout.visibility = if (!it.isNullOrEmpty()) VISIBLE else INVISIBLE
        }
    }

    private fun initView(): Unit {
        bd.btnExport.setOnClickListener { exportToExcel(it) }
    }

    /* Checks if external storage is available for read and write */
    fun isExternalStorageWritable() =
        Environment.MEDIA_MOUNTED == Environment.getExternalStorageState()

    /* Checks if external storage is available to at least read */
    fun isExternalStorageReadable(): Boolean {
        val state: String = Environment.getExternalStorageState()
        return Environment.MEDIA_MOUNTED == state ||
                Environment.MEDIA_MOUNTED_READ_ONLY == state
    }


    private fun exportToExcel(v: View) {
        PermissionX.init(this.activity)
            .permissions(Manifest.permission.WRITE_EXTERNAL_STORAGE)
            .request { allGranted, grantedList, deniedList ->
                if (!allGranted) {
                    toast(activity, getString(R.string.request_storage_write))
                }
            }
        flangeViewModel.saveToExcel(v.context)
    }

}